package com.ruoyi.web.wrapper;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.wrapper.BaseControllerWrapper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

public class MerchantDataPushCountInfoWrapper extends BaseControllerWrapper {

    public MerchantDataPushCountInfoWrapper(Map<String, Object> single) {
        super(single);
    }

    public MerchantDataPushCountInfoWrapper(List<Map<String, Object>> multi) {
        super(multi);
    }

    // 方法用于计算比率并将结果存入map
    private void calculateRate(Map<String, Object> map, String key, BigDecimal numerator, BigDecimal denominator) {
        if (ObjectUtil.isAllNotEmpty(numerator, denominator) && denominator.compareTo(BigDecimal.ZERO) != 0) {
            // 计算比率并保留四位小数
            BigDecimal rate = numerator.divide(denominator, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
            // 将结果存入 map 中，保留两位小数并添加百分号
            map.put(key, String.format("%.2f%%", rate));
        } else {
            map.put(key, "0%");
        }
    }

    @Override
    public void wrapTheMap(Map<String, Object> map) {

        try {

            // 获取各项数据
            BigDecimal checkNumber = getBigDecimalValue(map.get("checkNumber"));
            BigDecimal checkSuccessNumber = getBigDecimalValue(map.get("checkSuccessNumber"));
            BigDecimal registerNumber = getBigDecimalValue(map.get("registerNumber"));
            BigDecimal registerSuccessNumber = getBigDecimalValue(map.get("registerSuccessNumber"));



            // 检查空值
            if (ObjectUtil.isAllNotEmpty(checkNumber, checkSuccessNumber,registerNumber,registerSuccessNumber)) {
                // 计算撞库成功率
                calculateRate(map, "zhuangkuRate", checkSuccessNumber, checkNumber);

                // 计算注册成功率
                calculateRate(map, "zhuceRate", registerSuccessNumber, registerNumber);

            } else {
                map.put("zhuangkuRate", "0%");
                map.put("zhuceRate", "0%");
            }

        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    // 方法用于将对象转换为BigDecimal
    private BigDecimal getBigDecimalValue(Object obj) {
        if (obj instanceof BigDecimal) {
            return (BigDecimal) obj;
        } else if (obj instanceof Integer) {
            return new BigDecimal((Integer) obj);
        } else if (obj instanceof String) {
            try {
                return new BigDecimal((String) obj);
            } catch (NumberFormatException e) {
                // 如果转换失败，返回0
                return BigDecimal.ZERO;
            }
        } else {
            // 其他情况返回0
            return BigDecimal.ZERO;
        }
    }
}
